package com.ag.score.thread.service;

import com.ag.common.tools.DateUtil;
import com.ag.score.content.ApplicationContextProvider;
import com.ag.score.entity.TConfig;
import com.ag.score.entity.TRecord;
import com.ag.score.entity.TUser;
import com.ag.score.mapper.TConfigMapper;
import com.ag.score.mapper.TRecordMapper;
import com.ag.score.mapper.TUserMapper;
import com.ag.score.util.DayParam;
import com.ag.score.util.ScoreParam;

import com.redis.RedisKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DecimalFormat;

import java.util.HashMap;
import java.util.List;

public class ThreadService {


    protected final static Logger logger = LoggerFactory.getLogger(ThreadService.class);
    protected TConfigMapper tConfigMapper = ApplicationContextProvider.getBean(TConfigMapper.class);
    protected TRecordMapper tRecordMapper = ApplicationContextProvider.getBean(TRecordMapper.class);
    protected TUserMapper tUserMapper = ApplicationContextProvider.getBean(TUserMapper.class);
    public void processRecord(){

        int hour = DateUtil.getHour();
        if(DayParam.endHour != hour){
            return;
        }
        double endData = 0;
        String val = RedisKit.getString(ScoreParam.dataRedisKey);
        if(val !=null){
            try {
                endData =   new Double(val);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("ThreadService.processRecord error="+e.getMessage());
            }
        }
        if(endData==0) {
            //从数据库取值
            TConfig dataConfig = tConfigMapper.selectById(ScoreParam.dataDbId);
            if (dataConfig == null) {
                logger.error("ThreadService.processRecord endData = null"  );
                return;
            }
        }
        if(endData == 0){
            logger.error("ThreadService.processRecord endData= 0 " );
            return ;
        }
        double startData = 0;
         val = RedisKit.getString(ScoreParam.dataStartRedisKey);
        if(val !=null){
            try {
                startData =   new Double(val);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("ThreadService.processRecord error="+e.getMessage());
            }
        }
        if(startData == 0){
            logger.error("ThreadService.processRecord startData= 0 " );
            return ;
        }
        double upScoreSum = 0;
        double downScoreSum = 0;

        HashMap<String,Object> param = new  HashMap<String,Object>();
        param.put("status",0);
        param.put("recordtype",DayParam.recordType);

        List<TRecord> recordList = tRecordMapper.queryPage(param);
        if(recordList.size() == 0){
            return;
        }
        for(int i=0;i<recordList.size();i++){
            TRecord record = recordList.get(i);
            record.setEnddata(endData);
            if(record.getType() == 1){
                upScoreSum = upScoreSum + record.getUsescore();
            }else{
                downScoreSum = downScoreSum + record.getUsescore();
            }
        }
        if(startData > endData){
            if(upScoreSum == 0){
                //积分返回
                scoreBack(recordList);
            }else{
                //分配
                scoreWin(recordList,-1,upScoreSum/downScoreSum);

            }
        }else if(startData < endData){
            if(downScoreSum == 0){
                //积分返回
                scoreBack(recordList);
            }else{
                //分配
                scoreWin(recordList,1,downScoreSum/ upScoreSum);
            }

        }else{
            for(int i=0;i<recordList.size();i++){
                TRecord record = recordList.get(i);
                record.setStatus(1);
                record.setResscore(0);

                tRecordMapper.updateById(record);
            }
        }

    }

    private void scoreWin(List<TRecord> recordList,int type,double score){

        for(int i=0;i<recordList.size();i++){
            TRecord record = recordList.get(i);
            record.setStatus(1);
            if(record.getType() == type) {
                double winscore = getFormatTwo(record.getUsescore() *score);

                record.setResscore(winscore);
                tRecordMapper.updateById(record);
                TUser user = tUserMapper.selectById(record.getUid());
                if (user != null) {
                    user.setScore(user.getScore() + record.getResscore()+record.getUsescore());
                    tUserMapper.updateById(user);
                }
            }else{
                record.setResscore(-record.getUsescore());
                tRecordMapper.updateById(record);
            }
        }
    }

    private void scoreBack(List<TRecord> recordList){
        for(int i=0;i<recordList.size();i++){
            TRecord record = recordList.get(i);
            record.setStatus(1);
            record.setResscore(0);
            tRecordMapper.updateById(record);
            TUser user = tUserMapper.selectById(record.getUid());
            if(user!=null){
                user.setScore(user.getScore() + record.getUsescore());
                tUserMapper.updateById(user);
            }
        }
    }
    /**
     * 格式化double
     * @param dnum
     * @return
     */
    protected static  double  getFormatTwo(double  dnum){
        DecimalFormat df=new DecimalFormat(".##");
        return new Double(df.format(dnum));
    }




}
